//
//  MessPSViewController1.m
//  specialine
//
//  Created by 往返网络 on 17/3/17.
//  Copyright © 2017年 com. All rights reserved.
//

#import "MessPSViewController1.h"  //通过手机验证码验证1
#import "PublicMethod.h"

#define begin_x 30.0/W_BASE*SCREEN_W

//定义获取验证码URL
#define URL_SAVEPS [NSString stringWithFormat:@"%@/Appcustomernew/Personal/changePwddByCode?type=get",BASE_URL]
@interface MessPSViewController1 ()<UITextFieldDelegate>
//开辟多线程定时器，在后台执行，比NSTimer更自然

@property (nonatomic,strong) dispatch_source_t timer;
@property (nonatomic,strong)AFHTTPSessionManager * manger;


@end
@implementation MessPSViewController1

{

    UILabel * firstlabel;
    
    UITextField * yanzhenmatf; //验证码
    
    UITextField * newpstf;  //新密码
    
    UIButton * sendbtn; //重新发送
    
    UISwitch * newswitch; //新密码switch
    
    UIButton * savebtn; //保存按钮
    
    

}
- (void)viewWillAppear:(BOOL)animated{
    
    
    self.navigationController.navigationBar.hidden = YES;
    
    self.tabBarController.tabBar.hidden = YES;
    
    
}

- (void)viewWillDisappear:(BOOL)animated{
    
    self.navigationController.navigationBar.hidden = NO;
    
    self.tabBarController.tabBar.hidden = NO;
    
    if (_timer) {
        
        dispatch_source_cancel(_timer);
        
    }
    sendbtn.backgroundColor = [UIColor colorWithRed:238/255.0 green:240/255.0 blue:239/255.0 alpha:1];
    
    [sendbtn setTitle:@"重新发送" forState:UIControlStateNormal];
    
     sendbtn.layer.borderColor = [UIColor colorWithRed:238/255.0 green:240/255.0 blue:239/255.0 alpha:1].CGColor;

}

- (void)viewDidLoad {
    
    
    [super viewDidLoad];
    
    [self createUI];
    
    [self loadTimer];
    
    
    
}

- (void)loadTimer{
    
    __block NSInteger time = 59; //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    _timer= dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(_timer, ^{
        
        if(time <= 0){ //倒计时结束，关闭
            
            dispatch_source_cancel(_timer);
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置按钮的样式
                [sendbtn setTitle:@"重新发送" forState:UIControlStateNormal];
                
                [sendbtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                
                sendbtn.backgroundColor = COLORRGBA(51, 153, 255, 1);
                
                sendbtn.userInteractionEnabled = YES;
                
                
            });
            
        }else{
            
            int seconds = time % 60;
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置按钮显示读秒效果
                [sendbtn setTitle:[NSString stringWithFormat:@"已发送(%.2ds)", seconds] forState:UIControlStateNormal];
                [sendbtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
                
                sendbtn.backgroundColor = [UIColor colorWithRed:231/255.0 green:234/255.0 blue:232/255.0 alpha:1];
                
                sendbtn.userInteractionEnabled = NO;
            });
            time--;
            
        }
    });

    dispatch_resume(_timer);

}




- (void)createUI{
    
    
    self.view.backgroundColor = COLORRGBA(239, 239, 239, 1);
    
    UIView * titleview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_W, 128.0/1334*SCREEN_H)];
    
    titleview.backgroundColor =  COLORRGBA(7, 24, 57, 1);
    
    [self.view addSubview:titleview];
    
    
    float fontsize = 18;
    
    float corensize = 17;
    
    fontsize = SCREEN_H < 667 ? 16 : 20 ;
    
    corensize = SCREEN_H < 667 ? 15 : 19 ;
    
    
    if (SCREEN_H == 667) {
        
        fontsize = 18;
        
        corensize = 17;
        
    }
    
    UIButton * leftlable  = [[UIButton alloc]initWithFrame:CGRectMake(0, 20+14.0/1334*SCREEN_H, 80.0/W_BASE*SCREEN_W, 60.0/1334.0*SCREEN_H)];
    
    [leftlable setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    
    leftlable.titleLabel.font = [UIFont fontWithName:@"iconfont" size:fontsize+3];
    
    [leftlable setTitle:@"\U0000e697" forState:UIControlStateNormal];
    
    [leftlable.titleLabel setTextAlignment:NSTextAlignmentCenter];
    
    [leftlable addTarget:self action:@selector(enterClick:) forControlEvents:UIControlEventTouchUpInside];
    
    [titleview addSubview:leftlable];
    
    UILabel * titlelab = [[UILabel alloc]initWithFrame:CGRectMake(0, CGRectGetMinY(leftlable.frame), SCREEN_W, CGRectGetHeight(leftlable.frame))];
    
    titlelab.textAlignment = NSTextAlignmentCenter;
    
    titlelab.textColor = [UIColor whiteColor];
    
    titlelab.font = [UIFont systemFontOfSize:fontsize - 1];
    
    titlelab.text = @"修改密码";
    
    [titleview addSubview:titlelab];
    //
    
    firstlabel = [[UILabel alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(titleview.frame), SCREEN_W, 80.0/H_BASE*SCREEN_H)];
    
    firstlabel.font = [UIFont systemFontOfSize:fontsize - 6];
    
    [self.view addSubview:firstlabel];
    
    firstlabel.backgroundColor  = COLORRGBA(239, 239, 239, 1);
    
    NSString  * phone = [[NSUserDefaults standardUserDefaults]objectForKey:USERDEFAULTS_PHONE];
    
    NSString * startstr = [phone substringToIndex:3];
    
    NSString * endstr = [phone substringFromIndex:7];
    
    firstlabel.text  = [NSString stringWithFormat:@"短信已发送至%@****%@,请注意查收",startstr,endstr];
    
    firstlabel.textAlignment = NSTextAlignmentCenter;
    
    firstlabel.textColor = COLORRGBA(102, 102, 102, 1);
    
    UIView * view1 = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(firstlabel.frame), SCREEN_W, 160.0/H_BASE*SCREEN_H)];
    
    view1.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:view1];
    
    UIView * breakline = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMidY(view1.frame), SCREEN_W, 1)];
    
    breakline.backgroundColor = COLORRGBA(239, 239, 239, 1);
    
    [self.view addSubview:breakline];
    
    //验证码
    
    yanzhenmatf = [[UITextField alloc]initWithFrame:CGRectMake(begin_x, 0, 345.0/W_BASE*SCREEN_W, 80.0/H_BASE*SCREEN_H)];
    
    yanzhenmatf.placeholder = @"短信验证码";
    
    [view1 addSubview:yanzhenmatf];
    
    yanzhenmatf.font = [UIFont systemFontOfSize:fontsize - 4];
    
    yanzhenmatf.delegate  = self;
    
    // 新密码
    
    newpstf = [[UITextField alloc]initWithFrame:CGRectMake(begin_x, 80.0/H_BASE*SCREEN_H, CGRectGetWidth(yanzhenmatf.frame), CGRectGetHeight(yanzhenmatf.frame))];
    
    newpstf.placeholder = @"新密码";
    newpstf.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
    
    [view1 addSubview:newpstf];
    
    newpstf.font = [UIFont systemFontOfSize:fontsize -4];
    
    newpstf.delegate  = self;
    
    newpstf.secureTextEntry = YES;
    
    //重新发送
    
    sendbtn = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_W - 190.0/W_BASE*SCREEN_W, 15.0/H_BASE*SCREEN_H, 160.0/W_BASE*SCREEN_W, 50.0/H_BASE*SCREEN_H)];
    
    [sendbtn setBackgroundColor:COLORRGBA(239, 239, 239, 1)];
    
    [view1 addSubview:sendbtn];
    
    [sendbtn setTitleColor:COLORRGBA(102, 102, 102, 1) forState:UIControlStateNormal];
    
    [sendbtn setTitle:@"已发送(60s)" forState:UIControlStateNormal];
    
    sendbtn.titleLabel.font = [UIFont systemFontOfSize:fontsize - 5];
    
    // 重新启动定时器。。
    
    [sendbtn addTarget:sendbtn action:@selector(loadTimer) forControlEvents:UIControlEventTouchUpInside];
    
    
    sendbtn.layer.cornerRadius = 12;
    
    sendbtn.clipsToBounds = YES;
    
    
    newswitch = [[UISwitch alloc]initWithFrame:CGRectMake(SCREEN_W - 132.0/W_BASE*SCREEN_W, CGRectGetMaxY(breakline.frame)+9.0/H_BASE*SCREEN_H, 102.0/W_BASE*SCREEN_W, 62.0/H_BASE*SCREEN_H)];
    
    
    [newswitch setOnTintColor:COLORRGBA(51, 153, 255, 1)];
    
    [self.view addSubview:newswitch];
    
//    newswitch.userInteractionEnabled = NO; //不可用。。
    
    [newswitch addTarget:self action:@selector(switchclick) forControlEvents:UIControlEventValueChanged];
    
    
    savebtn = [[UIButton alloc]initWithFrame:CGRectMake(begin_x, CGRectGetMaxY(view1.frame)+65.0/H_BASE*SCREEN_H, 690.0/H_BASE*SCREEN_H, 80.0/H_BASE*SCREEN_H)];
    
    [savebtn setBackgroundColor:COLORRGBA(59, 214, 117, 0.5)];
    
    [self.view addSubview:savebtn];
    
    savebtn.titleLabel.font = [UIFont systemFontOfSize:fontsize - 3];
    
    [savebtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    [savebtn addTarget:self action:@selector(savePSnow:) forControlEvents:UIControlEventTouchUpInside];
    
    savebtn.layer.cornerRadius = 2;
    
    savebtn.clipsToBounds = YES;
    
    [savebtn setTitle:@"保存" forState:UIControlStateNormal];
    
    savebtn.userInteractionEnabled = NO;
    
    
}



- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    
    //一旦有输入，就变色
    
    NSString * textstring = [textField.text stringByReplacingCharactersInRange:range withString:string];
    
    if (textstring.length >= 1) {
        
        [savebtn setBackgroundColor:COLORRGBA(59, 214, 117, 1)];

        savebtn.userInteractionEnabled = YES;
    }
    
 
    
    return YES;
    
}

- (void)switchclick{
    

    if (newswitch.isOn) {
        
        
        newpstf.secureTextEntry = NO;

        
    }else{
    
    
        newpstf.secureTextEntry = YES;
        
    }

    
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{

    [self.view endEditing:YES];
    
    return YES;

}
- (void)enterClick:(UIButton *)btn{
    
    
    [self.navigationController popViewControllerAnimated:YES];
    
    
}


- (void)savePSnow:(UIButton *)btn{

    
    if (yanzhenmatf.text.length != 6) {
        
        ALERT(@"提示", @"验证码位数不对", self, @"确定", nil);
        
        return;
        
    }
    if (newpstf.text.length <6 ) {
        
        ALERT(@"提示", @"密码位数有误", self, @"确定", nil);
        
        return;

    }else if (newpstf.text.length >16){
    
        ALERT(@"提示", @"密码位数有误", self, @"确定", nil);
        
        return;

    }
    
    
    [self checkCode];
    
    
    
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{


    [self.view endEditing:YES];
    

}

#pragma mark  - -- - - - -   校验验证码 - - - - - - - - - --
- (void)checkCode{
    
    
    
    //开始动画
    UIImageView * im = [PublicMethod startAnimation];
    
    
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    
    NSString * token = [user objectForKey:USER_TOCKE];
    
    NSString * mobile = [user objectForKey:USERDEFAULTS_PHONE];
    
    NSString * url = [NSString stringWithFormat:@"%@&token=%@&mobile=%@&msgCode=%@&password=%@",URL_SAVEPS,token,mobile,yanzhenmatf.text,newpstf.text];
    
    
    [self.manger GET:url parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        
        if (responseObject) {
            
            NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            
            NSInteger code = [dict[@"code"]integerValue];
            
            if (code == 0) {
                
                //获取验证码成功
                
                [im stopAnimating];
                
                ALERT(@"提示", dict[@"info"], self, @"确定", nil);
                
                [self.navigationController popViewControllerAnimated:YES];

                
            }else{
                
                [im stopAnimating];
                
                
                ALERT(@"提示", dict[@"info"], self, @"确定", nil);
                
            }
            
            
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        [im stopAnimating];
        
        ALERT(@"提示", @"网络请求失败", self, @"确定", nil);
        
    }];
    
    
    
}



- (AFHTTPSessionManager*)manger{
    
    _manger = [AFHTTPSessionManager manager];
    
    _manger.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    _manger.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", nil];
    
    
    return _manger;
    
    
    
}

- (void)didReceiveMemoryWarning {
    
    
    [super didReceiveMemoryWarning];
    
    
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
